package Server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Chat_Server {
	public static ArrayList<Socket> connectionArray = new ArrayList<Socket>();
	public static ArrayList<String> currentUsers = new ArrayList<String>();

	public static void main(String args[]) throws IOException {
		try {
			int port = 7665;
			ServerSocket server = new ServerSocket(port);
			System.out.println("Waiting for clients...");
			while (true) {
				Socket sock = server.accept();
				connectionArray.add(sock);
				System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
				addUserName(sock);
				Chat_Server_Return chat = new Chat_Server_Return(sock);
				Thread x = new Thread(chat);
				x.start();
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public static void addUserName(Socket x) throws IOException {
		Scanner input = new Scanner(x.getInputStream());
		String userName = input.nextLine();
		currentUsers.add(userName);
		for (int i = 1; i <= Chat_Server.connectionArray.size(); i++) {
			Socket temp_sock = (Socket) Chat_Server.connectionArray.get(i-1);
			PrintWriter out = new PrintWriter(temp_sock.getOutputStream());
			out.println("#?!"+currentUsers);
			out.flush();
		}

	}

}
